﻿using Blazored.LocalStorage;
using IdentityServer4Blazor.Shared.IdentityServerModel;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Security.Claims;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace IdentityServer4Blazor.Client
{
    public class CustomAuthStateProvider : AuthenticationStateProvider
    {
        private readonly IJSRuntime _jSRuntime;

        public CustomAuthStateProvider(IJSRuntime jSRuntime)
        {
            _jSRuntime = jSRuntime;
        }
        public override async Task<AuthenticationState> GetAuthenticationStateAsync()
        {
            var a = await _jSRuntime.InvokeAsync<object>("getUser");
            var clims = new List<Claim>();
            if (a != null)
            {
                var b = JsonSerializer.Serialize(a);
                Log.Information(b);
                var d = JsonDocument.Parse(b);
                foreach (var item in d.RootElement.EnumerateObject())
                {
                    System.Console.WriteLine(item.Name);
                    //if (item.Name.Equals("expires_at"))
                    //{

                    //    var ts = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
                    //    var time = item.Value.GetInt64();
                    //    Log.Information(ts.ToString());
                    //    Log.Information(time.ToString());
                    //    if (ts > time)
                    //    {
                    //        var userNull = new ClaimsPrincipal(new ClaimsIdentity());
                    //        //Log.Information(user.Identity.IsAuthenticated.ToString());
                    //        return new AuthenticationState(userNull);
                    //    }
                    //}
                    //if (item.Name.Equals("access_token"))
                    //{
                    //    _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", item.Value.GetString());
                    //}
                    if (item.Name.Equals("profile"))
                    {
                        foreach (var profile in item.Value.EnumerateObject())
                        {
                            if (!profile.Name.Equals("amr"))
                            {
                                if (profile.NameEquals("role")&& !profile.Value.ValueKind.ToString().Equals("String"))
                                {
                                    var roles = profile.Value.EnumerateArray().ToList();
                                    foreach (var role in roles)
                                    {
                                        clims.Add(new Claim(profile.Name, role.ToString()));
                                    }
                                }
                                else
                                {
                                    clims.Add(new Claim(profile.Name, profile.Value.ToString()));
                                }
                                
                            }
                        }
                    }
                }
                var identity = new ClaimsIdentity(clims, "IdentityUser","name","role");
                var user = new ClaimsPrincipal(identity);
                return new AuthenticationState(user);
            }
            else
            {
                
                var user = new ClaimsPrincipal(new ClaimsIdentity());
                Log.Information(user.Identity.IsAuthenticated.ToString());
                //Log.Information(user.Identity.IsAuthenticated.ToString());
                return new AuthenticationState(user);
            }
        }
        public void MarkUserAsAuthenticated()
        {
            Log.Information("maksure");
            NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
        }
    }
}
